import * as WebSocketService from '@/services/websocket';

/**
 * WebSocket Vue插件
 * 提供全局的WebSocket管理功能
 */
const WebSocketPlugin = {
  install(Vue, options = {}) {
    // 将WebSocket服务挂载到Vue原型上
    Vue.prototype.$websocket = WebSocketService;
    
    // 创建全局的WebSocket状态管理
    const websocketState = Vue.observable({
      isConnected: false,
      reconnectCount: 0,
      isReconnecting: false,
      messageQueueLength: 0,
      lastMessage: null,
      lastError: null,
      connectionTime: null
    });
    
    // 将状态挂载到Vue原型上
    Vue.prototype.$websocketState = websocketState;
    
    // 监听WebSocket事件，更新状态
    WebSocketService.addEventListener('connected', (data) => {
      websocketState.isConnected = true;
      websocketState.isReconnecting = false;
      websocketState.reconnectCount = 0;
      websocketState.connectionTime = new Date();
      websocketState.lastError = null;
      
      // 显示连接成功提示
      if (Vue.prototype.$message) {
        // Vue.prototype.$message.success('WebSocket连接成功');
      }
    });
    
    WebSocketService.addEventListener('disconnected', () => {
      websocketState.isConnected = false;
      websocketState.connectionTime = null;
      
      // 显示连接断开提示
      if (Vue.prototype.$message) {
        // Vue.prototype.$message.warning('WebSocket连接已断开');
      }
    });
    
    WebSocketService.addEventListener('error', (data) => {
      websocketState.lastError = data.error;
      websocketState.isConnected = false;
      
      // 显示连接错误提示
      if (Vue.prototype.$message) {
        // Vue.prototype.$message.error('WebSocket连接错误');
      }
    });
    
    WebSocketService.addEventListener('reconnecting', (data) => {
      websocketState.isReconnecting = true;
      websocketState.reconnectCount = data.count;
      
      // 显示重连提示
      if (Vue.prototype.$message) {
        // Vue.prototype.$message.info(`正在重连... (${data.count}/5)`);
      }
    });
    
    WebSocketService.addEventListener('maxReconnectReached', (data) => {
      websocketState.isReconnecting = false;
      
      // 显示最大重连次数提示
      if (Vue.prototype.$message) {
        // Vue.prototype.$message.error(`重连失败，已达到最大重连次数 (${data.count})`);
      }
    });
    
    WebSocketService.addEventListener('message', (data) => {
      websocketState.lastMessage = data;
    });
    
    // 添加全局方法
    Vue.prototype.$initWebSocket = (uid) => {
      return WebSocketService.initWebSocket(uid);
    };
    
    Vue.prototype.$closeWebSocket = () => {
      return WebSocketService.closeWebSocket();
    };
    
    Vue.prototype.$sendWebSocketMessage = (type, message, uid) => {
      return WebSocketService.sendMessage(type, message, uid);
    };
    
    // 添加全局混入，提供WebSocket生命周期管理
    Vue.mixin({
      beforeDestroy() {
        // 组件销毁时移除WebSocket事件监听器
        if (this._websocketListeners) {
          this._websocketListeners.forEach(({ eventName, callback }) => {
            WebSocketService.removeEventListener(eventName, callback);
          });
        }
      },
      
      methods: {
        /**
         * 添加WebSocket事件监听器（组件级别）
         * @param {string} eventName 事件名
         * @param {Function} callback 回调函数
         */
        $onWebSocket(eventName, callback) {
          if (!this._websocketListeners) {
            this._websocketListeners = [];
          }
          
          WebSocketService.addEventListener(eventName, callback);
          this._websocketListeners.push({ eventName, callback });
        },
        
        /**
         * 移除WebSocket事件监听器（组件级别）
         * @param {string} eventName 事件名
         * @param {Function} callback 回调函数
         */
        $offWebSocket(eventName, callback) {
          if (this._websocketListeners) {
            const index = this._websocketListeners.findIndex(
              listener => listener.eventName === eventName && listener.callback === callback
            );
            
            if (index > -1) {
              this._websocketListeners.splice(index, 1);
            }
          }
          
          WebSocketService.removeEventListener(eventName, callback);
        }
      }
    });
    
    // 添加全局指令，用于显示WebSocket状态
    Vue.directive('websocket-status', {
      bind(el, binding) {
        const updateStatus = () => {
          const status = websocketState.isConnected ? 'connected' : 'disconnected';
          el.className = `websocket-status ${status}`;
          el.textContent = status === 'connected' ? '已连接' : '未连接';
        };
        
        updateStatus();
        
        // 监听状态变化
        el._websocketStatusWatcher = Vue.observable(websocketState);
        el._websocketStatusWatcher.$watch('isConnected', updateStatus);
      },
      
      unbind(el) {
        if (el._websocketStatusWatcher) {
          el._websocketStatusWatcher.$destroy();
        }
      }
    });
  }
};

export default WebSocketPlugin;
